package com.example.demo.controller;

import com.example.demo.common.ResponseMessage;
import com.example.demo.pojo.Customer;
import com.example.demo.pojo.Order;
import com.example.demo.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/order/")
public class OrderController {
    @Autowired
    private IOrderService iOrderService;
    @RequestMapping("create.do")
    public ResponseMessage create(Order order) {
        int order1 = iOrderService.addOrder(order);
        ResponseMessage msg = null;
        if(order1 == 1) {
            msg = new ResponseMessage(0,null,order);
            return msg;
        }
        else{
            msg = new ResponseMessage(1,"创建订单失败");
            return msg;
        }
    }

    @RequestMapping("get_order_cart_product.do")
    //查询报错 java.lang.NullPointerException: null空指针异常
    //可能是sql写错了？long类型数据有问题？
    public ResponseMessage orderProductInfo(HttpSession session, Long orderId) {
        Customer user = (Customer) session.getAttribute("currentCustomer");
        ResponseMessage msg = null;
        if(user == null){
            msg = new ResponseMessage(1,"用户未登录");
            return msg;
        }
        else {
            msg = iOrderService.getProductInfo(orderId);
            msg = new ResponseMessage(0,null, msg.getData());
            return msg;
        }
    }


    @RequestMapping("list.do")
    //嵌套查询 没有权限status：1 未实现
    public ResponseMessage list(HttpSession session) {
        Customer user = (Customer) session.getAttribute("currentCustomer");
        ResponseMessage msg = null;
        if(user == null){
            msg = new ResponseMessage(10,"用户未登录，请登录");
            return msg;
        }
        else {
            int userId = user.getId();
            msg = iOrderService.getOrderList(userId);
            msg = new ResponseMessage(0,null, msg.getData());
            return msg;
        }
    }

    //@RequestMapping("detail.do") 订单详情的嵌套查询 未实现

    @RequestMapping("cancel.do")
    //此订单已付款，无法被取消status：1 未实现
    public ResponseMessage cancel(long orderNo) {
        ResponseMessage msg = null;
        Integer order = iOrderService.getStatus(orderNo);
        if(order == 20){
            msg = new ResponseMessage(1,"此订单已付款，无法被取消");
            return msg;
        }
        else {
            iOrderService.deleteOrder(orderNo);
            msg = new ResponseMessage(0,null);
            return msg;
        }
    }
}
